/**
 * @Author：ming
 * @Date：2023/10/4 1:29 AM
 * @Filename：Lc1248
 */

/**
 * @author ming
 */
public class Lc1248 {
    public int numberOfSubarrays(int[] nums, int k) {
        int len = nums.length;
        //存储下标相邻的连续偶数的个数
        int[] before = new int[len];
        int[] after =new int[len];

        for (int i = 0; i < len; i++) {
            if(i==0){
                before[i]=0;
            }else if(nums[i-1]%2==0){
                before[i]=before[i-1]+1;
            }else {
                before[i]=0;
            }
        }


        for (int i = len-1; i >=0 ; i--) {
            if(i==len-1){
                after[i]=0;
            }else if(nums[i+1]%2==0){
                after[i]=after[i+1]+1;
            }else {
                after[i]=0;
            }
        }

        int l =0;
        int r =0;
        int countJ =0;
        int count =0;
        while (r<len){
            if(nums[r]%2==1){
                countJ++;
            }
            while (countJ==k){
                if(nums[l++]%2==1){
                    countJ--;
                }
                if(countJ<k){
                    count += (before[l-1]+1)*(after[r]+1);
                }
            }

            r++;
        }

        return count;
    }
}
